package com.lupan.tomcatStudy.activemq.base;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 说明：
 *
 * @author lupan
 * @version 2016/5/30 15:17
 */
public class JSMProducer {

    private static final String userName = ActiveMQConnection.DEFAULT_USER;
    private static final String password = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String brokerUrl = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static final int sendNum = 10;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageProducer messageProducer;

        try {
            connectionFactory = new ActiveMQConnectionFactory(userName, password, brokerUrl);
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("mq");
            //创建消息生产者
            messageProducer = session.createProducer(destination);

            send(session,messageProducer);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void send(Session session, MessageProducer producer) throws JMSException {
        for (int i = 0; i < sendNum; i++) {
            TextMessage textMessage = session.createTextMessage("ActiveMQ 发送消息" + i);
            System.out.println("发送消息：Activemq 发送消息" + i);
            producer.send(textMessage);
        }
    }
}
